import { useState, useEffect, useCallback } from "react";
import { Button, message } from "antd";
import CommonLoading from "@/components/CommonLoading";
import Api from "../../service";
import styles from "./index.module.less";

export default ({ templateId, kuaimaiItem, commonParams, handleOk, handleCancel }) => {
	const [loading, setLoading] = useState(false);

	const [canRefresh, setRefresh] = useState(false);

	const { templateName, ecStoreIds, sizeWidth, sizeHeight, id, applyModule, labelType, sort, viewContent } = kuaimaiItem;

	useEffect(() => {
		KMTEMPLATE.initEditLabel({
			...commonParams,
			id: templateId,
			printFlag: true,
			save: res => {
				if (res.status == "success") {
					setRefresh(true);
				}
			}
		});
	}, []);

	useEffect(() => {
		if (canRefresh) {
			getRefreshTemplate();
		}
	}, [canRefresh]);

	const kuaimaiTemplateFindOne = useCallback(templateId => {
		return new Promise((resolve, reject) => {
			KMTEMPLATE.getTemplateList({
				...commonParams,
				templateId,
				current: 1,
				pageSize: 10,
				callback: res => {
					if (res?.list?.[0]) {
						resolve(res.list[0]);
					} else {
						reject();
					}
				}
			});
		});
	}, []);

	const getRefreshTemplate = () => {
		kuaimaiTemplateFindOne(templateId).then(obj => {
			if (obj?.tagConfig) {
				const { width, height } = JSON.parse(obj.tagConfig);
				const params = {
					templateName,
					applyModule,
					ecStoreIds,
					kmTemplateCode: templateId,
					sizeWidth: width,
					labelType,
					sizeHeight: height,
					sort,
					viewContent,
					id: id
				};
				handleOperaDB(params);
			}
		});
	};

	//操作数据库
	const handleOperaDB = async params => {
		setLoading(true);
		let res;
		res = await Api.updateKuaimaiOp(params);
		if (res.success) {
			handleOk();
		}
		setLoading(false);
	};

	return (
		<div className={styles.fullScreenModal}>
			<div className={styles.modalHeader}>
				<h3>{`编辑标签`}</h3>
				<Button type="primary" onClick={handleCancel}>
					返回ERP
				</Button>
			</div>
			<div id="kuaimaiiframeviewDelivery" style={{ flex: 1 }}></div>
			<CommonLoading loading={loading} />
		</div>
	);
};
